/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.restapi;

import com.fasterxml.jackson.databind.ObjectMapper;
import cz.muni.fi.pa165.portalnahouby.api.dto.PickerDTO;
import cz.muni.fi.pa165.portalnahouby.api.serviceinterface.PickerService;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

/**
 *
 * @author Tomáš Čejka
 */
@Controller
@RequestMapping("/rest/pickers/*")
public class PickerServlet extends HttpServlet {

    @Autowired
    private PickerService pickerService;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String pathInfo = request.getPathInfo();
        try {
            if (pathInfo != null && pathInfo.matches("/\\d+")) {
                response.setContentType("application/json");
                ObjectMapper mapper = new ObjectMapper();
                PickerDTO picker = pickerService.findPicker(Long.parseLong(pathInfo.substring(1)));
                mapper.writeValue(response.getOutputStream(), picker);
            } else {

                response.setContentType("application/json");
                ObjectMapper mapper = new ObjectMapper();
                mapper.writeValue(response.getOutputStream(), pickerService.getAllPickers());
            }
        } catch (NullPointerException e) {
            response.sendError(response.SC_BAD_REQUEST, "Picker with ID " + pathInfo.substring(1) + " doensn't exist!");
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");

        ObjectMapper mapper = new ObjectMapper();

        PickerDTO picker = mapper.readValue(request.getInputStream(), PickerDTO.class);
	
	    if (picker.getIsAdmin() == null) {
		    picker.setIsAdmin(false);
	    }

        try {
            if (picker.getId() != null) {
                PickerDTO pickerExistTest = pickerService.findPicker(picker.getId());

                pickerService.editPicker(picker);

            } else {
                pickerService.addPicker(picker);
            }
        } catch (NullPointerException e) {
            response.sendError(response.SC_BAD_REQUEST, "Picker with ID " + picker.getId() + " doensn't exist!");
        }

    }
    
	@Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");

        ObjectMapper mapper = new ObjectMapper();

        PickerDTO picker = mapper.readValue(req.getInputStream(), PickerDTO.class);
	
	if (picker.getIsAdmin() == null) {
			picker.setIsAdmin(false);
		}

        try {
            if (picker.getId() != null) {
                PickerDTO pickerExistTest = pickerService.findPicker(picker.getId());

                pickerService.editPicker(picker);

            } else {
                pickerService.addPicker(picker);
            }
        } catch (NullPointerException e) {
            resp.sendError(resp.SC_BAD_REQUEST, "Picker with ID " + picker.getId() + " doensn't exist!");
        }

    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");

        String pathInfo = request.getPathInfo();
        try {
            if (pathInfo != null && pathInfo.matches("/\\d+")) {
                response.setContentType("application/json");
                ObjectMapper mapper = new ObjectMapper();
                Long pickerId = Long.parseLong(pathInfo.substring(1));

                PickerDTO pickerExistTest = pickerService.findPicker(pickerId);
                pickerService.deletePicker(pickerId);

            }
        } catch (NullPointerException e) {
            Long pickerId = Long.parseLong(pathInfo.substring(1));
            response.sendError(response.SC_BAD_REQUEST, "Picker with ID " + pickerId + " doensn't exist!");
        }

    }
}
